# -*- coding: utf-8 -*-
import time 

def read_cpu_usage(): 
    """
    
    """ 
    lines = open("/proc/stat").readlines() 
    for line in lines: 
        #print "l = %s" % line 
        l = line.split() 
        if len(l) < 5: 
            continue 
        if l[0].startswith('cpu'): 
            return l;
    return {} 

def getCup_info():
    """parser cup info
    
    """
    cpustr = read_cpu_usage()
    #cpu usage=[(user_2 +sys_2+nice_2) - (user_1 + sys_1+nice_1)]/(total_2 - total_1)*100 
    usni1 = long(cpustr[1]) + long(cpustr[2]) + long(cpustr[3]) + long(cpustr[5]) + long(cpustr[6]) + long(cpustr[7]) + long(cpustr[4])
    usn1 = long(cpustr[1]) + long(cpustr[2]) + long(cpustr[3])
    
    time.sleep(2)
    cpustr = read_cpu_usage()
    usni2 = long(cpustr[1]) + long(cpustr[2]) + float(cpustr[3]) + long(cpustr[5]) + long(cpustr[6]) + long(cpustr[7]) + long(cpustr[4])
    usn2 = long(cpustr[1]) + long(cpustr[2]) + long(cpustr[3])
    #usni2=long(cpustr[1])+long(cpustr[2])+float(cpustr[3])+long(cpustr[4])
    
    cpuper = (usn2 - usn1) / (usni2 - usni1)
    #s = "CPUTotal used percent =%.4f \r\n" % (cpuper * 100)
    return cpuper  


print getCup_info()